import Vue from 'vue'
import Vuex from 'vuex'
import userMoudles from '@/store/moudles/user'

Vue.use(Vuex)

// vuex 插件：用于保存购物车中选购的商品数据到本地存储中（数据持久化）
const savePlugin = store => {
  // 添加对每次 mutation 调用后执行的任务的监听
  store.subscribe((mutations, state) => {
    switch (mutations.type) {
      case 'SET_USERNAME':
        localStorage.setItem('username', mutations.playload)
        break
      case 'SET_AVATARURL':
        localStorage.setItem('avatarUrl', mutations.playload)
        break
      case 'SET_TOKEN':
        localStorage.setItem('token', mutations.playload)
        break
      default:
        // 将购物车商品保存到 localStorage 中（JSON.stringify()序列化）
        localStorage.setItem('cart', JSON.stringify(state.cart))
    }
  })
}

const store = new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production', // 在开发环境下开启严格模式，生产环境下关闭
  plugins: [savePlugin],
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || []
  },
  getters: {
    // 全选
    isAllChecked (state) {
      return state.cart.every(item => item.isChecked)
    },

    // 计算总价
    totalMoney (state) {
      return Math.floor(state.cart.reduce((sum, item) => {
        if (item.isChecked) {
          sum += item.price * item.amount
        }
        return sum
      }, 0) * 100)
    }
  },
  mutations: {
    // 添加至购物车
    addToCart (state, playload) {
      const flag = state.cart.some(item => item.id === playload.id)
      if (flag) {
        state.cart = state.cart.map(prod => {
          const copy = { ...prod }
          if (copy.id === playload.id) {
            copy.amount += playload.amount
          }
          return copy
        })
      } else {
        state.cart.push({
          ...playload,
          isChecked: true
        })
      }
    },
    // 删除商品
    removeFromCart (state, id) {
      state.cart = state.cart.filter(item => item.id !== id)
    },

    // 修改数量
    changeAmount (state, { id, amount }) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        if (item.id === id) {
          copy.amount = amount
        }
        return copy
      })
    },

    // 切换选中状态
    toggleChecked (state, id) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        if (item.id === id) {
          copy.isChecked = !copy.isChecked
        }
        return copy
      })
    },

    // 切换全选状态
    toggleCheckedAll (state, preChecked) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        copy.isChecked = !preChecked
        return copy
      })
    }
  },
  actions: {},
  modules: {
    user: userMoudles
  }
})

export default store
